package com.jun.flower.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jun.flower.bean.PageResult;
import com.jun.flower.bean.TbBuycarExample.Criteria;
import com.jun.flower.bean.TbFlowers;
import com.jun.flower.bean.TbOrders;
import com.jun.flower.bean.TbOrdrsitem;
import com.jun.flower.bean.TbOrdrsitemExample;
import com.jun.flower.bean.TbUser;
import com.jun.flower.service.FlowerService;
import com.jun.flower.service.OrderService;
import com.jun.flower.service.OrderitemService;
import com.jun.flower.service.UserService;

@Controller
public class OrdersController {
	@Autowired
	protected OrderService orderService;
	@Autowired
	protected OrderitemService orderitemservice;
	@Autowired
	protected FlowerService flowerService;
	@Autowired
	protected UserService userService;
	
	@RequestMapping("/orders/show")
	public String showOrders(Model model,Integer id){
		//根据订单id查询订单信息
		TbOrders orders = orderService.getOrdersById(id); 
		model.addAttribute("orders", orders);
		
		//查询根据订单号鲜花信息
		List<TbFlowers> listFlower = new ArrayList<>();
		List<TbOrdrsitem> list =  orderitemservice.getOrderitemByOrdersId(orders.getId());
		List<Integer> quantitys = new ArrayList<>();

		Double panel= 0.0;
		if(list!=null || list.size()!=0) {
			for(int i=0;i<list.size();i++) {
				if(list.get(i).getFlowersId()!=0) {
				Integer quantity = list.get(i).getFlowesQuantity();
				TbFlowers flowers = flowerService.getFlowerById(list.get(i).getFlowersId());
				listFlower.add(flowers);
				quantitys.add(quantity);
				panel += flowers.getPrice()*quantity;
				}
			}
		}
		model.addAttribute("quantitys", quantitys);
		model.addAttribute("listFlower", listFlower);
		model.addAttribute("panel",panel);
		//根据用户id查询用户信息
		TbUser user = userService.getUserById(orders.getUserId());
		model.addAttribute("user", user);
		return "order-show";
	}
	
	@RequestMapping("/orders/list")
	public String showOrdersList(Model model,@RequestParam(defaultValue="1")Integer pageNum,@RequestParam(defaultValue="5")Integer pageSize){
		PageResult<TbOrders> pageResult = orderService.getOrdersList(pageNum,pageSize);
		model.addAttribute("odersList",pageResult.getList());
		model.addAttribute("page", pageResult);
		return "order-list";
	}
	
	@RequestMapping("/order/check/oredernum")
	@ResponseBody
	public Map checkOrderNum(String oredernum) {
		boolean result = orderService.checkOrderNum(oredernum);
		Map data = new HashMap<>();
		data.put("status", result);
		return data;
	}
	
	@RequestMapping("/order/save")
	public String addOrder(TbOrders order,HttpServletRequest request) {
		//把用户数据添加到数据库中
		orderService.addOrder(order);
		
		TbOrdrsitem ordersitem = new TbOrdrsitem();
		TbOrders orders = orderService.getOrdersByNum(order.getOredernum());
		ordersitem.setOrdersId(orders.getId());

		int flowersId = Integer.parseInt(request.getParameter("flowersId"));
		ordersitem.setFlowersId(flowersId);

		orderitemservice.addOrderitem(ordersitem);
		//跳转到用户列表页面
		return "redirect:/orders/list";
	}
	
	@RequestMapping("/order/delete")
	@ResponseBody
	public Map deleteOrder(String ids) {
		//先删除orderitem里的有关数据
		String[] arrStr = ids.split("\\,");
		List<Integer> list = new ArrayList<>();
		for(int i=0;i<arrStr.length;i++) {
			list.add(Integer.parseInt(arrStr[i]));	
		}
		for(Integer i : list) {
			List<TbOrdrsitem> result = orderitemservice.getOrderitemByOrdersId(i);
			if(result !=null && result.size()!=0) {
				orderitemservice.deleteOrderitemByordersId(i);
			}
		}
		Boolean result = orderService.deleteOrder(ids);
		Map data = new HashMap<>();
		data.put("state", result);
		return data;
	}
	
	@RequestMapping("/orders/update")
	public String updateOrder(Model model, Integer id) {
		// 根据订单id查询订单信息
		TbOrders orders = orderService.getOrdersById(id);
		model.addAttribute("orders", orders);

		// 查询根据订单号鲜花信息
		List<TbFlowers> listFlower = new ArrayList<>();
		List<TbOrdrsitem> list = orderitemservice.getOrderitemByOrdersId(orders.getId());
		List<Integer> quantitys = new ArrayList<>();

		Double panel = 0.0;
		if (list != null || list.size() != 0) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getFlowersId() != 0) {
					Integer quantity = list.get(i).getFlowesQuantity();
					TbFlowers flowers = flowerService.getFlowerById(list.get(i).getFlowersId());
					listFlower.add(flowers);
					quantitys.add(quantity);
					panel += flowers.getPrice() * quantity;
				}
			}
		}
		model.addAttribute("quantitys", quantitys);
		model.addAttribute("listFlower", listFlower);
		model.addAttribute("panel", panel);
		// 根据用户id查询用户信息
		TbUser user = userService.getUserById(orders.getUserId());
		model.addAttribute("user", user);
		return "order-update";
	}
	
	@RequestMapping("/orders/updateById")
	public String updateOrderById(TbOrders orders) {
		orderService.updateOrderById(orders);
		return "redirect:/orders/list";
	}
	
	@RequestMapping("/orderitem/delete")
	public String orderitem (Integer flowersId,Integer id) {
		orderitemservice.deleteOrderitem(flowersId);
		return "redirect:/orders/update?id="+id;
	}
	
	@RequestMapping("/buy/flower")
	public String buyflower(Model model,@RequestParam("listFlower")String list,String userId,String quantitys) throws Exception{
		String[] strs = quantitys.split("\\,");
		List<Integer> quantityList = new ArrayList<>();
		for(int i=0;i<strs.length;i++) {
			quantityList.add(Integer.parseInt(strs[i]));
		}
		
		model.addAttribute("quantityList", quantityList);
		//jackson对象
		ObjectMapper mapper = new ObjectMapper();
		//使用jackson将json转为List<TbFlowers>
		JavaType jt = mapper.getTypeFactory().constructParametricType(ArrayList.class, TbFlowers.class);   
		List<TbFlowers> listFlower =  (List<TbFlowers>)mapper.readValue(list, jt);
		model.addAttribute("listFlower", listFlower);
		
		int id = Integer.parseInt(userId); 
		TbUser user = userService.getUserById(id);
		model.addAttribute("user", user);
	
		String oredernum = OrdersController.getUUID();
		model.addAttribute("oredernum", oredernum);

		String ordertime = OrdersController.getCurrentTime();
		model.addAttribute("ordertime",ordertime);
		
		return "web-buy";
	}
	public static String getUUID(){
        UUID uuid=UUID.randomUUID();
        String str = uuid.toString(); 
        String uuidStr=str.replace("-", "");
        return uuidStr;
      }
	public static String getCurrentTime() {
		Date date = new Date();
		String time = String.format("%tF", date);
		String form = String.format("%tT", date);
		return time+ " "+ form;
	}
	@RequestMapping("/buy/carflower")
	public String buyCarflower(Model model,Integer flowerId,String userId,String quantity) throws Exception{

		List<Integer> quantityList = new ArrayList<>();
		quantityList.add(Integer.valueOf(quantity));
		model.addAttribute("quantityList", quantityList);
		
		List<TbFlowers> listFlower = new ArrayList<>();
		TbFlowers flower=flowerService.getFlowerById(flowerId);
		if(flower!=null) {
			listFlower.add(flower);
		}
		model.addAttribute("listFlower", listFlower);
		
		int id = Integer.parseInt(userId); 
		TbUser user = userService.getUserById(id);
		model.addAttribute("user", user);
	
		String oredernum = OrdersController.getUUID();
		model.addAttribute("oredernum", oredernum);

		String ordertime = OrdersController.getCurrentTime();
		model.addAttribute("ordertime",ordertime);
		
		return "web-buy";
	}
	
	@RequestMapping("/buy/order")
	public String buyOrder(Model model,TbOrders order,String ids,String quantitys) {
		orderService.addOrder(order);
		String[] strs = ids.split("\\,");
		List<Integer> flowersIds = new ArrayList<>();
		for(int i=0;i<strs.length;i++) {
			flowersIds.add(Integer.parseInt(strs[i]));
		}
		String[] quantitysStr = quantitys.split("\\,");
		List<Integer> quantitysInt = new ArrayList<>();
		for(int i=0;i<quantitysStr.length;i++) {
			quantitysInt.add(Integer.parseInt(quantitysStr[i]));
		}
		
		for(int i=0;i<flowersIds.size();i++) {
			TbOrdrsitem ordersitem = new TbOrdrsitem();
			TbOrders orders = orderService.getOrdersByNum(order.getOredernum());
			ordersitem.setOrdersId(orders.getId());
			ordersitem.setFlowersId(flowersIds.get(i));
			ordersitem.setFlowesQuantity(quantitysInt.get(i));
			orderitemservice.addOrderitem(ordersitem);
		}
		return"web-success";
	}
}

